import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus
} from "@nestjs/common";
import { AjaxResult } from "../class/ajaxResult";


/**
 * @Description: 全局异常过滤器
 * @author zhaojiuyi
 * @date 2023/4/7
 */
@Catch()
export class ExceptionsFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    console.info("全局异常过滤器：", exception);

    // console.info("host", JSON.stringify(host));

    const ctx = host.switchToHttp();
    const response = ctx.getResponse();

    const {status,message} = this.getContext(exception)

    response.header("Content-Type", "application/json; charset=utf-8");
    response.json(
      AjaxResult.error(status, message)
    );
  }

  getContext(exception:unknown){
    let status:number = 500
    let message:any = "服务器内部错误"
    if (exception instanceof HttpException){
      status = exception.getStatus();
      const response = exception.getResponse();
      message = typeof response === "string" ? response : response['message']
    }
    return {status,message}
  }

}
